﻿using Sunny.UI;
using System.Collections.Generic;
using CoreShop.Model;
using CoreShop.Services;
using System;
using CoreShop.Model.UI;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Collections;
using System.Security.Policy;
using SqlSugar.Extensions;
using Sunny.UI.Win32;
using System.Windows.Forms;
using System.ComponentModel;
using CoreShop.Library;
using System.Linq;
using NPOI.SS.Formula.Functions;
using System.Drawing;
using static CoreShop.Library.GlobalEnumVars;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.Data;
using System.IO;
using MySqlX.XDevAPI.Relational;
using SqlSugar;
using NPOI.Util;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Runtime.InteropServices.ComTypes;
using CoreShop.Model.FromBody;
using static System.Windows.Forms.AxHost;
using NPOI.POIFS.Properties;
using System.Xml.Linq;
using System.Threading;
using Org.BouncyCastle.Asn1.Ocsp;
using CoreShop.App.Units.Interface;
using System.Threading.Tasks;
using Loading;

namespace CoreShop.App
{
    public partial class frmFoodList : UIForm
    {
        public bool returnValue;
        private long selectTypeId = 0;
        List<corecmsfood> foodlstSource = new List<corecmsfood>();
        List<corecmsprintscheme> printschemes = new List<corecmsprintscheme>();
        List<corecmsfoodprintscheme> foodprintschemes = new List<corecmsfoodprintscheme>();
        public corecmsfoodcategory foodcategory = null;
        private DateTime dtGetFood = DateTime.Now.AddDays(-1);
        OpaqueCommand cmd1 = new OpaqueCommand();
        public int mPageIndex = 0;
        public string number = "";
        private long foodTypeId = 0;
        private string locaStr = "";
        public frmFoodList()
        {
            InitializeComponent();
            this.ShowFullScreen = AppConstVars.showFullScreen;
        }

        private void Food_Load(object sender, System.EventArgs e)
        {
            mPageIndex = 1;
            btnSelectPrinter.SelectedIndex = 0;
            LoadFoodPrintSchemes();//加截商品打印方案和打印方案数据
            LoadPrintSchemes();
            LoadFoodCategroy();
            LoadDataList(0, number);
        }

        private void LoadFoodPrintSchemes()
        {
            var printSchemeIds = new corecmsprintschemedetailServices().AsQueryable()
                .Where(p => p.billtypeId == (int)GlobalEnumVars.PrintbillType.Label && p.selectedFlag == true)
                .Select(p=>p.printSchemeId).ToList();
            if ((printSchemeIds == null) || (printSchemeIds.Count == 0)) return;  //没有启用标签打印机

            var printschemeData = new corecmsprintschemeServices().AsQueryable()
                .Where(p=> printSchemeIds.Contains(p.id) && p.retryCount == (int)GlobalEnumVars.RetryCount.JoinGoods).ToList();
            if ((printschemeData == null) || (printschemeData.Count == 0)) return;  //没有启用标签打印机

            foodprintschemes = new corecmsfoodprintschemeServices().QueryAsync(0);

            //是否有标签打印方案
            var where1 = Expressionable.Create<corecmsprintschemedetail>();
            where1 = where1.And(p => p.billtypeId == (int)GlobalEnumVars.PrintbillType.Label && p.selectedFlag == true);
            
            var labelList = new corecmsprintschemedetailServices().AsQueryable().Where(where1.ToExpression()).ToList();

            var where = Expressionable.Create<corecmsprintscheme>();
            if (labelList != null && labelList.Count > 0)
            {
                var labelIds = labelList.Select(p => p.printSchemeId).Distinct().ToList();
                where = where.And(p => labelIds.Contains(p.id));
            } 
            else
                where = where.And(p => p.id == 0);

            printschemes = new corecmsprintschemeServices().AsQueryable()
                .Where(where.ToExpression()).OrderBy(p => p.id).ToList();

            if (this.cmbPrinterList.Items.Count <= 0)
            {
                var printschemeList = new corecmsprintschemeServices().AsQueryable()
                    .Where(where.ToExpression()).OrderBy(p => p.id).ToList();

                #region 加载打印机
                //this.cmbPrinterList.Items.Clear();
                cmbPrinterList.DataSource = printschemeList;
                cmbPrinterList.DisplayMember = "gearName";
                cmbPrinterList.ValueMember = "id";
                #endregion
            }
        }

        #region 加载信息列表

        private Expressionable<corecmsfood, corecmsfoodspec> GetExpressionable(long mFoodTypeId, string sName,int stand)
        {
            int sPrinterType = btnSelectPrinter.SelectedIndex;
            int printSchemeId = 0;
            if (!string.IsNullOrEmpty(cmbPrinterList.Text)) printSchemeId = cmbPrinterList.SelectedValue.ObjToInt();

            var where = Expressionable.Create<corecmsfood, corecmsfoodspec>();
            where = where.And((f, s) => f.isDelete == false && f.sellStatus != 0 && s.onLine == true);
            if (!string.IsNullOrEmpty(sName))
                where = where.And((f, s) => f.name.Contains(sName) || f.number.Contains(sName) || s.code.Contains(sName)
                || f.byName.Contains(sName) || f.helpCode.Contains(sName) || f.pinYin.Contains(sName));

            if (sPrinterType > 0)
            {
                var foodprintschemeIds = new corecmsfoodprintschemeServices().AsQueryable()
                     .Where(p => p.printSchemeId == printSchemeId).Select(p => p.foodId).ToList();
                if (sPrinterType == 1)
                    where = where.And((f, s) => !foodprintschemeIds.Contains(f.id));
                else
                    where = where.And((f, s) => foodprintschemeIds.Contains(f.id));
            }

            if (mFoodTypeId > 0)
            {
                List<long> typeIds = new List<long>();
                if (mFoodTypeId <= AppConstVars.sysStore.corpId)
                {
                    typeIds = new corecmsfoodcategoryServices().AsQueryable()
                    .Where(p => p.tenantId == mFoodTypeId).Select(p => p.id).ToList();
                }
                else
                {
                    typeIds = new corecmsfoodcategoryServices().GetChildrenIds(mFoodTypeId);
                }
                if (typeIds.Count > 0)
                    where = where.And((f, s) => f.foodTypeId == mFoodTypeId || typeIds.Contains(f.foodTypeId));
                else
                    where = where.And((f, s) => f.foodTypeId == mFoodTypeId);
            }

            if (stand >= 0)
            {
                if (stand > 10)
                    where = where.And((f, s) => f.type > 0);
                else where = where.And((f, s) => f.type == stand);
            }

            return where;
        }

        private void LoadDataList(Int64 sTypeID, string sName)
        {
            foodTypeId = sTypeID;
            locaStr = sName;
            var count = 0;
            foodlstSource = new corecmsfoodServices().QueryPageAsync(ref count, mPageIndex, btnPg.PageSize, GetExpressionable(sTypeID, sName,-1));
            btnPg.TotalCount = count;
            this.dgvFoodList.AutoGenerateColumns = false;
            this.dgvFoodList.DataSource = foodlstSource;
            lblTotal.Text = $"共{count}条,{btnPg.PageSize}条/每页";
            btnSave.Enabled = false;
            BindFoodPrintSchemes();
        }

        private void LoadFoodCategroy()
        {
            new FoodUtil().LoadFoodCategroy(tvFood);
            LoadDataList(0, "");
        }

        /// <summary>
        /// 添加打印方案列
        /// </summary>
        private void LoadPrintSchemes()
        {
            string sColumnName;
            string headerText;
            foreach (var item in printschemes)
            {
                sColumnName = string.Format("ID_{0}", item.id);
                headerText = item.gearName;

                DataGridViewCheckBoxColumn column = new DataGridViewCheckBoxColumn();
                column.HeaderText = headerText; // 设置列标头文本
                column.Name = sColumnName; // 设置列名称                
                column.Tag = item.id;
                column.FalseValue = 0;
                column.TrueValue = 1;
                dgvFoodList.Columns.Add(column); // 将列添加到 DataGridView 控件中                
                dgvFoodList.Columns[sColumnName].HeaderText = headerText;
                dgvFoodList.Columns[sColumnName].Visible = true;
                dgvFoodList.Columns[sColumnName].Tag = item.id;
                dgvFoodList.Columns[sColumnName].AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
                //SetFoodPrintScheme(sColumnName, item.id);//绑定表格的打印方案字段
            }

            /* 暂未启用
            sColumnName = "btnTitle";
            headerText = "修改";

            DataGridViewCellStyle cellStyle = new System.Windows.Forms.DataGridViewCellStyle();
            cellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            cellStyle.Font = new System.Drawing.Font("微软雅黑", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

            DataGridViewLinkColumn column_task = new DataGridViewLinkColumn();
            column_task.HeaderText = headerText; // 设置列标头文本
            column_task.Name = sColumnName; // 设置列名称
            column_task.LinkColor = System.Drawing.SystemColors.ControlDark;
            column_task.DataPropertyName = "byName";
            column_task.DefaultCellStyle = cellStyle;
            dgvFoodList.Columns.Add(column_task); // 将列添加到 DataGridView 控件中                
            dgvFoodList.Columns[sColumnName].HeaderText = headerText;
            dgvFoodList.Columns[sColumnName].Visible = true;
            dgvFoodList.Columns[sColumnName].ReadOnly = true;
            dgvFoodList.Columns[sColumnName].AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
            */
        }

        /// <summary>
        /// 添加打印方案列
        /// </summary>
        private void BindFoodPrintSchemes()
        {
            long foodId;
            for (int i = 0; i < dgvFoodList.Rows.Count; i++)
            {
                foodId = CommFunc.ConvertToBigInt(dgvFoodList.Rows[i].Cells["id"].Value);
                string sColumnName;
                foreach (var item in printschemes)
                {
                    sColumnName = string.Format("ID_{0}", item.id);
                    if (dgvFoodList.Columns.Contains(sColumnName) == true)
                    {
                        var foodprintscheme = foodprintschemes.Find(p => p.foodId == foodId && p.printSchemeId == item.id);
                        if (foodprintscheme != null)
                        {
                            dgvFoodList.Rows[i].Cells[sColumnName].Value = 1;
                        }
                        else
                        {
                            dgvFoodList.Rows[i].Cells[sColumnName].Value = 0;
                        }
                    }
                }
            }
        }

        #endregion

        private void btnSerach_Click(object sender, EventArgs e)
        {
            mPageIndex = 1;
            LoadDataList(0, txtSearch.Text.Trim());
        }

        private void ubtn_exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dgvFoodList_CellDoubleClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            btnUpdate_Click(null, null);
        }


        private void tvFood_AfterSelect(object sender, TreeViewEventArgs e)
        {
            selectTypeId = CommFunc.ConvertToInt64(e.Node.Tag);
            foodcategory = new corecmsfoodcategoryServices().GetById(selectTypeId);
            LoadDataList(selectTypeId, "");
        }

        private void btnPg_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            mPageIndex = pageIndex;
            LoadDataList(0, txtSearch.Text.Trim());
        }

        private void SetFoodPrintchemes(long foodId, int foodSchemeId, int value)
        {
            var foodSchemes = foodprintschemes.Where(p => p.foodId == foodId && p.printSchemeId == foodSchemeId).ToList();
            if ((foodSchemes == null) || (foodSchemes.Count == 0))
            {
                if (value == 1)
                {
                    var foodprintscheme = new corecmsfoodprintscheme();
                    foodprintscheme.foodId = foodId;
                    foodprintscheme.foodSpecId = 0;
                    foodprintscheme.printSchemeId = foodSchemeId;
                    foodprintschemes.Add(foodprintscheme);
                }
                return;
            }
            foreach (var foodScheme in foodSchemes)
            {
                foodScheme.printSchemeId = 0;
            }
            if (value == 1)
            {
                var foodScheme1 = foodSchemes.FirstOrDefault();
                foodScheme1.printSchemeId = foodSchemeId;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            ShowWaitForm("数据保存中，请稍后.....");
            try
            {
                LoadFoodPrintSchemes();
                long foodId;
                int foodSchemeId;
                string sColumnName;
                for (int i = 0; i < dgvFoodList.Rows.Count; i++)
                {
                    foreach (var item in printschemes)
                    {
                        sColumnName = string.Format("ID_{0}", item.id);//借该字段用做序号绑定dgvFoodList的printer*字段
                        foodId = CommFunc.ConvertToBigInt(dgvFoodList.Rows[i].Cells["id"].Value);
                        if (dgvFoodList.Columns.Contains(sColumnName) == true)
                        {
                            foodSchemeId = CommFunc.ConvertToInt32(dgvFoodList.Columns[sColumnName].Tag);
                            var mValue = CommFunc.ConvertToInt32(dgvFoodList.Rows[i].Cells[sColumnName].Value);
                            SetFoodPrintchemes(foodId, foodSchemeId, mValue);
                        }
                    }
                }

                var foodprintschemeServices = new corecmsfoodprintschemeServices();
                var bl = foodprintschemeServices.InsertOrUpdate(foodprintschemes);
                foodprintschemeServices.Delete(p => p.printSchemeId == 0);

                //List<corecmsfood> corecmsfoods = (List<corecmsfood>)dgvFoodList.DataSource;
                //if (!new corecmsfoodServices().UpdatePriceAsync(corecmsfoods))
                if (!bl)
                {
                    HideWaitForm();
                    UIMessageBox.Show("保存失败", "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
                    return;
                }
                ShowSuccessTip("保存成功");
                LoadFoodPrintSchemes();
                LoadDataList(foodTypeId, locaStr);
            }
            finally
            {
                HideWaitForm();
            }
        }

        private void dgvFoodList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            btnSave.Enabled = true;
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {

        }

        private DataTable CheckExcelFileContent(DataTable dt)
        {
            //dt.Columns.Add("typeId", typeof(string));
            dt.Columns.Add("提示", typeof(string));
            //List<corecmsfoodcategory> typeList = new corecmsfoodcategoryServices().QueryAsync(0, "").ToList();
            bool checkRs = true;
            foreach (DataRow row in dt.Rows)
            {
                var strTip = string.Empty;
                // 获取当前行的目标列的值
                var spec = row["spec"].ToString();
                var food = row["food"].ToString();
                var fooType = row["商品分类"].ToString();
                //List<corecmsfoodcategory> types = typeList.Where(p => p.name == type).ToList();
                // 检查值是否合格，这里使用了一个示例条件，你可以根据具体需要进行修改
                DataRow[] chekSpecRow = dt.Select("spec='" + spec + "'");
                DataRow[] checkTypeRow = dt.Select("food='" + food + "' and   商品分类<>'" + fooType + "'");
                if (chekSpecRow.Length > 1)
                {
                    strTip = "存在相同规格商品;";
                    checkRs = false;
                }
                if (checkTypeRow.Length > 0)
                {
                    strTip += "同一商品不允许设置不同分类;";
                    checkRs = false;
                }
                row["提示"] = strTip;
                // 如果不合格，则增加一列到DataTable中
            }

            //if (checkRs)
            //    dt.Columns.Remove("提示");
            return dt;
        }
        private void GetOrderFromExcel(string toFileFullPath)
        {
            DataTable dt = new DataTable("Table_New");
            dt.Columns.Add("商品分类", typeof(string));
            dt.Columns.Add("商品编码", typeof(string));
            dt.Columns.Add("商品名称", typeof(string));
            dt.Columns.Add("规格", typeof(string));
            dt.Columns.Add("销售价", typeof(decimal));
            dt.Columns.Add("会员价", typeof(decimal));
            dt.Columns.Add("出品部门", typeof(string));
            dt.Columns.Add("spec", typeof(string));
            dt.Columns.Add("food", typeof(string));
            FileStream fs = new FileStream(toFileFullPath, FileMode.Open);//打开myxls.xls文件
            HSSFWorkbook wk = new HSSFWorkbook(fs);   //把xls文件中的数据写入wk中
            for (int i = 0; i < wk.NumberOfSheets; i++)  //NumberOfSheets是myxls.xls中总共的表数
            {
                ISheet sheet = wk.GetSheetAt(i);   //读取当前表数据
                if (sheet.LastRowNum > 50000)
                {
                    UIMessageBox.Show("单次导入不能超过500条", "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
                    return;
                }
                for (int j = 0; j <= sheet.LastRowNum; j++)  //LastRowNum 是当前表的总行数
                {
                    var row1 = sheet.GetRow(j);  //读取当前行数据
                    if ((row1 != null) && (j > 0))
                    {
                        DataRow dr = dt.NewRow();
                        dr["商品分类"] = CommFunc.ConvertToString(row1.GetCell(0));
                        dr["商品编码"] = CommFunc.ConvertToString(row1.GetCell(1));
                        dr["商品名称"] = CommFunc.ConvertToString(row1.GetCell(2));
                        dr["规格"] = CommFunc.ConvertToString(row1.GetCell(3));
                        dr["销售价"] = CommFunc.ConvertToDecimal(row1.GetCell(4));
                        dr["会员价"] = CommFunc.ConvertToDecimal(row1.GetCell(5));
                        dr["出品部门"] = CommFunc.ConvertToString(row1.GetCell(6));
                        dr["spec"] = string.Concat(CommFunc.ConvertToString(row1.GetCell(1)), "_", CommFunc.ConvertToString(row1.GetCell(2)), "_", CommFunc.ConvertToString(row1.GetCell(3)));
                        dr["food"] = string.Concat(CommFunc.ConvertToString(row1.GetCell(1)), "_", CommFunc.ConvertToString(row1.GetCell(2)));
                        dr.EndEdit();
                        dt.Rows.Add(dr);
                    }
                }
            }
            if (!CheckExcelFile(dt)) return;
            dt = CheckExcelFileContent(dt);
            //var frm = new frmFoodImport(dt);
            //if (frm.ShowDialog() == DialogResult.OK)
            //{
            //    menuFoodDown_Click(null, null);
            //}
            //frm.Dispose();
        }

        private bool CheckExcelFile(DataTable dt)
        {
            if (dt.Columns.Contains("商品分类") == false)
            {
                UIMessageBox.Show("【商品分类】的列不存在，无法导入。");
                return false;
            }
            if (dt.Columns.Contains("商品编码") == false)
            {
                UIMessageBox.Show("【商品编码】的列不存在，无法导入。");
                return false;
            }
            if (dt.Columns.Contains("商品名称") == false)
            {
                UIMessageBox.Show("【商品名称】的列不存在，无法导入。");
                return false;
            }
            if (dt.Columns.Contains("规格") == false)
            {
                UIMessageBox.Show("【规格】的列不存在，无法导入。");
                return false;
            }
            if (dt.Columns.Contains("销售价") == false)
            {
                UIMessageBox.Show("【销售价】的列不存在，无法导入。");
                return false;
            }
            if (dt.Columns.Contains("会员价") == false)
            {
                UIMessageBox.Show("【会员价】的列不存在，无法导入。");
                return false;
            }
            if (dt.Columns.Contains("出品部门") == false)
            {
                UIMessageBox.Show("【出品部门】的列不存在，无法导入。");
                return false;
            }
            return true;
        }

        private void dgvFoodList_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //uiButton2.ShowContextMenuStrip(cmsPrintschemeOpt, 0, uiButton2.Height);
            if (dgvFoodList.Rows.Count == 0) return;
            if (dgvFoodList.Columns[e.ColumnIndex].Name.Substring(0, 3) == "ID_")
            {
                int newValue = 0;
                var value = CommFunc.ConvertToInt32(dgvFoodList.Rows[0].Cells[e.ColumnIndex].Value);
                if (value == 0) newValue = 1;
                for (int i = 0; i < dgvFoodList.Rows.Count; i++)
                {
                    foreach (var item in printschemes)
                    {
                        dgvFoodList.Rows[i].Cells[e.ColumnIndex].Value = newValue;
                    }
                }
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            SetPrinterCheck(1);
        }

        /// <summary>
        /// //https://learn.microsoft.com/zh-cn/dotnet/desktop/winforms/controls/selected-cells-rows-and-columns-datagridview?view=netframeworkdesktop-4.8
        /// </summary>
        /// <param name="value"></param>
        private void SetPrinterCheck(int value)
        {
            Int32 selectedCellCount = dgvFoodList.GetCellCount(DataGridViewElementStates.Selected);
            if (selectedCellCount > 0)
            {
                if (dgvFoodList.AreAllCellsSelected(true))
                {
                    MessageBox.Show("All cells are selected", "Selected Cells");
                }
                else
                {
                    for (int i = 0; i < selectedCellCount; i++)
                    {
                        int rowId = dgvFoodList.SelectedCells[i].RowIndex;
                        int colId = dgvFoodList.SelectedCells[i].ColumnIndex;
                        string sColName = dgvFoodList.Columns[colId].Name;
                        if (dgvFoodList.Columns[colId].Name.Substring(0, 3) == "ID_")
                        {
                            dgvFoodList.Rows[rowId].Cells[colId].Value = value;
                        }
                    }
                }
            }
            else
            {
                UIMessageBox.Show("请选择打印机区域的某些单元格，然后再点【取消打印】。");
            }
        }

        private void btnCancelAll_Click(object sender, EventArgs e)
        {
            SetPrinterCheck(0);
        }

        private void txtSearch_OkButtonClick(object sender, string value)
        {
            btnSerach_Click(null, null);
        }

        private void dgvFoodList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int mRowIndex = e.RowIndex;
            if (dgvFoodList.Columns[e.ColumnIndex].Name == "btnTitle")
            {
                Int64 foodId = CommFunc.ConvertToInt64(dgvFoodList.Rows[mRowIndex].Cells["id"].Value);
                //frmFoodEdit frm = new frmFoodEdit(foodId);
                //frm.ShowDialog();
                //frm.Dispose(); 
            }
        }

        private void dgvFoodList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int rowId = e.RowIndex;
            int colId = e.ColumnIndex;
            if ((rowId < 0) || (colId < 0)) return;

            if (dgvFoodList.Columns[colId].Name.Substring(0, 3) == "ID_")
            {
                int newValue = 0;
                var value = CommFunc.ConvertToInt32(dgvFoodList.Rows[rowId].Cells[colId].Value);
                if (value == 0) newValue = 1;
                dgvFoodList.Rows[rowId].Cells[colId].Value = newValue;
                txtSearch.Focus();
            }
        }

        private void btnExchange_Click(object sender, EventArgs e)
        {

        }

        private void menuFoodInport_Click(object sender, EventArgs e)
        {
            string sFileName = "";
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Title = "选择一个文件";
            openFileDialog1.Multiselect = true;
            openFileDialog1.Filter = "Excel文件|*.xls|Excel文件|*.xlsx";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                foreach (string fileName in openFileDialog1.FileNames)
                {
                    sFileName = fileName;
                }
            }

            if (string.IsNullOrEmpty(sFileName)) return;
            GetOrderFromExcel(sFileName);
        }

        private async void menuFoodDown_ClickAsync(object sender, EventArgs e)
        {
            TimeSpan timeDifference = DateTime.Now.Subtract(dtGetFood);
            if (timeDifference.TotalMinutes < 2)
            {
                UIMessageBox.Show("同步数据过于频繁,请稍后再试。");
                return;
            }

            cmd1.ShowOpaqueLayer(pnl_Form, 125, true);
            try
            {
                var exchange = new corecmsexchangeServices().GetDataById(AppConstVars.sysUser.storeId);
                string msg = "";
                List<corecmsfood> foodList = new List<corecmsfood>();
                var remoteService = new PosRemoteServices(AppConstVars.sysUser.ccessToken);
                var goodsResult = await FoodApiUtil.GetGoodDataList(AppConstVars.sysStore, AppConstVars.sysUser, exchange);

                remoteService.GetGoodCategoryList(AppConstVars.sysStore, AppConstVars.sysUser, exchange, ref msg);
                msg = string.Format("同步的商品数据为<{0}>条记录。<{1}>", goodsResult.count, goodsResult.msg);
                UIMessageBox.Show(msg);
                dtGetFood = DateTime.Now;
            }
            catch (Exception)
            {
            }
            finally { cmd1.HideOpaqueLayer(); }            
        }

        private void btnMore_Click(object sender, EventArgs e)
        {
            btnMore.ShowContextMenuStrip(cmsMore, 0, btnMore.Height);
        }

        private void menuAddFoodType_Click(object sender, EventArgs e)
        {
            ShowFoodCategoryInfo(new corecmsfoodcategory());
        }

        private void ShowFoodCategoryInfo(corecmsfoodcategory foodcategory)
        {
            frmFoodCategoryInfo frm = new frmFoodCategoryInfo(foodcategory);
            frm.ShowDialog();
            LoadFoodCategroy();
            frm.Dispose();
        }

        private void menuEditType_Click(object sender, EventArgs e)
        {
            if (foodcategory == null)
            {
                UIMessageBox.Show("没有选择分类，不能修改。");
                return;
            }
            ShowFoodCategoryInfo(foodcategory);
        }

        private void btnAddInfo_Click(object sender, EventArgs e)
        {
            if (!ProcessUtil.GetUserRoleAny(GlobalEnumVars.UserRoleType.addproduct, 0, false)) return;
            var foodModel = new corecmsfood();
            foodModel.foodTypeId = selectTypeId;
            SetFoodInfo(foodModel);
        }

        private void SetFoodInfo(corecmsfood foodInfo)
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.addproduct, 0)) return;
            frmFoodInfo frm = new frmFoodInfo(foodInfo.id, foodInfo.foodTypeId, "");            
            if (frm.ShowDialog() == DialogResult.OK)
            {
                LoadDataList(selectTypeId, txtSearch.Text.Trim());
            }
            if (frm.isNewCategory)
            {
                btnRefresh_Click(null, null);
            }
            //new FoodUtil().GetGoodsData(this);
            frm.Dispose();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (dgvFoodList.CurrentRow != null)
            {
                long foodId = CommFunc.ConvertToInt64(dgvFoodList.CurrentRow.Cells["id"].Value);
                corecmsfood food = new corecmsfoodServices().GetById(foodId);
                //SetFoodInfo(food);
            }
        }

        private void tsmTaskInfo_Click(object sender, EventArgs e)
        {
            //frmFoodTaskList frm = new frmFoodTaskList("", false);
            //frm.ShowDialog();
            //frm.Dispose();
        }

        private async void tsmFeedInfo_ClickAsync(object sender, EventArgs e)
        {
            if (!ProcessUtil.GetUserRoleAny(GlobalEnumVars.UserRoleType.addproduct, 0, true)) return;
            frmFoodInfo frm = new frmFoodInfo(0, 0, "", (int)GlobalEnumVars.GoodsSpuType.VirtualGoods);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                var exchange = new corecmsexchangeServices().GetById(AppConstVars.sysUser.storeId);
                if (exchange != null)
                {
                    var goodsResult = await FoodApiUtil.GetGoodDataList(AppConstVars.sysStore, AppConstVars.sysUser, exchange);
                }
                LoadDataList(selectTypeId, txtSearch.Text.Trim());
            }
            frm.Dispose();
        }

        private void btnSendScale_Click(object sender, EventArgs e)
        {
            frmFoodWeighing frm = new frmFoodWeighing();
            if (frm.ShowDialog() == DialogResult.Yes)
            {
            }
            frm.Dispose();
        }
                
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadFoodCategroy();
            LoadDataList(0, number);
        }

        private void tsmChgPriceList_Click(object sender, EventArgs e)
        {
            frmGoodsChgPrice frm = new frmGoodsChgPrice();
            frm.ShowDialog();
            frm.Dispose();
        }
    }
}